<template>
  <view class="login-wrap">
    <!-- #ifdef H5 -->
    <van-nav-bar @click-left="onClickLeft" left-arrow></van-nav-bar>
    <!-- #endif -->
    <view class="login-top">
      <view class="header">
        <view class="bg1"></view>
        <view class="bg2"></view>
        <view class="bg3"></view>
        <view class="bg4"></view>
        <view class="car"></view>
        <view class="text text-bold" v-html="title"></view>
      </view>
      <view class="title-wrap">
        <view class="title-action" :class="[action === '1' ? 'action1' : 'action2']"></view>
        <view :class="{ action: action === '1' }" @tap="tapAction('1')">手机号登录</view>
        <view :class="{ action: action === '2' }" @tap="tapAction('2')">账号密码登录</view>
      </view>
      <view class="login-form">
        <form v-if="action === '1'" class="form-wrap">
          <view class="input-wrap">
            <input
              placeholder-class="placeholder"
              v-model="form.account"
              placeholder="请输入手机号"
              maxlength="30" />
          </view>
          <view class="input-wrap">
            <input
              class="input-code"
              v-model="form.code"
              placeholder-class="placeholder"
              placeholder="请输入验证码"
              maxlength="10" />
            <button
              class="bnt-code"
              :class="{ 'bnt-disabled': codeObj.disabled }"
              :plain="true"
              :disabled="codeObj.disabled"
              @tap="tapCode">
              {{ codeObj.codeName }}
            </button>
          </view>
        </form>
        <form v-if="action === '2'" class="form-wrap">
          <view class="input-wrap">
            <input
              placeholder-class="placeholder"
              v-model="form.account"
              placeholder="请输入账号"
              maxlength="30" />
          </view>
          <view class="input-wrap">
            <input
              class="input-wrap"
              v-model="form.password"
              :password="isPwd"
              placeholder-class="placeholder"
              placeholder="请输入密码"
              maxlength="30" />
            <view
              class="iconfont icon-pwd"
              :class="[isPwd ? 'icon-pwd-close' : 'icon-pwd-open']"
              @tap="tapPwd"></view>
          </view>
        </form>
      </view>
      <view class="row">
        <view class="agreement-wrap">
          <view class="radio-wrap" :class="{ 'radio-radius': !checkAgreement }" @tap="tapAgreement">
            <icon v-if="checkAgreement" :type="'success'" :color="colors.systemColor" size="20" />
          </view>
          <text>我已阅读并同意</text>
          <text class="text1" @tap="tapAgreementUrl">《用户协议》</text>
        </view>
        <button
          class="forgot-pwd"
          :class="{ 'bnt-hidden': action === '1' }"
          :plain="true"
          @tap="tapForgot">
          重置密码
        </button>
      </view>
    </view>
    <view class="bnt-bottom" :style="bntTop">
      <button class="bnt-wrap bnt-login" @tap="tapLogin">登录</button>

      <!-- 微信授权登录 -->
      <!-- #ifdef MP-WEIXIN -->
      <button
        v-if="checkAgreement"
        class="bnt-wrap bnt-login-wx"
        :class="{ 'bnt-hidden': action !== '1' }"
        hover-class="none"
        open-type="getPhoneNumber"
        @getphonenumber="bindPhoneNumber">
        手机号快捷登录
      </button>
      <button
        v-else
        class="bnt-wrap bnt-login-wx"
        hover-class="none"
        :class="{ 'bnt-hidden': action !== '1' }"
        @tap="tapWx">
        手机号快捷登录
      </button>
      <!-- #endif -->

      <view class="tip">
        {{ action === '1' ? '手机号未注册情况下，将自动创建新账号' : '当前方式仅限企业账号' }}
      </view>
    </view>
    <PopupUser ref="popupUserRef"></PopupUser>
    <PopupAgreement ref="popupAgreementRef" @set-agreement="setAgreement"></PopupAgreement>
  </view>
</template>

<script lang="ts" setup>
import PopupUser from '@/components/popupUser/popupUser.vue';
import PopupAgreement from './popupAgreement.vue';
import {
  colors,
  setToken,
  setUserId,
  setOpenId,
  setMoreCharge,
  systemInfo,
  setToastInstance,
} from '@/mixins/info';
import { uniLogin } from '@/utils/api';
import {
  loginWithPassword,
  loginWithCode,
  sendPhoneVCode,
  loginWithWx,
} from '@/service/apis/login';
import { queryOpenId } from '@/service/apis/mine';
import { getMd5, backPage, noMultipleClicks, saveItem } from '@/utils/util';
import { getLocationInfo } from '@/utils/location';
// #ifdef MP-WEIXIN
import { useToast } from '@/components/wxToast';
setToastInstance(useToast());
// #endif

// 分享
onShareAppMessage(() => {
  return {
    title: '',
    path: '/pages/stationMap/stationMap',
  };
});

const title = import.meta.env.VITE_VUE_APP_TITLE;

const $toast: any = inject('$Toast');

const popupUserRef = ref();
const popupAgreementRef = ref();

const bntTop = ref('');
// #ifndef H5
const info: any = uni.getSystemInfoSync().safeArea;
if (info.width / info.bottom > 0.56) {
  const { proxy: vm } = getCurrentInstance()!;
  const query = uni.createSelectorQuery().in(vm);
  nextTick(() => {
    query
      .select('.login-top')
      .boundingClientRect((info: any) => {
        bntTop.value = `top: ${info.bottom}px`;
      })
      .exec();
  });
}
// #endif

// const jscode = await uniLogin('weixin');
// console.log('jscode------', jscode);

const getOpenId = async () => {
  const code = await uniLogin('weixin');
  if (!code) {
    return;
  }
  queryOpenId({ code: code }).then((res: any) => {
    if (res) {
      openid.value = res;
    }
  });
};

let page = ref('');
let openid = ref('');
onLoad((option: any) => {
  page.value = option.page || '/pages/stationMap/stationMap';
  if (option.type === 'qrcode') {
    (getApp().globalData as any).qType = '';
    page.value = `${option.page}?type=qrcode` || '/pages/stationMap/stationMap?type=qrcode';
  }
  getOpenId();
  // page.value = option.page || '/pages/stationMap/stationMap';

  tapCode = noMultipleClicks(tapCode);
  tapLogin = noMultipleClicks(tapLogin);
  tapWx = noMultipleClicks(tapWx);
  // bindPhoneNumber = noMultipleClicks(bindPhoneNumber);
});

// 切换登录类型
let action = ref('1');
let form = reactive({
  account: '',
  code: '',
  password: '',
});
let checkAgreement = ref(false); //是否勾选协议
const tapAction = (type: any) => {
  action.value = type;
  form = {
    account: '',
    code: '',
    password: '',
  };
};

// 验证码
let codeObj = reactive({
  codeName: '获取验证码',
  disabled: false,
  count: 120,
  timeout: 0,
});
let tapCode = () => {
  console.log('444444440=------------');
  if (!form.account) {
    $toast('请输入手机号');
    return;
  }
  if (!new RegExp(/^(1[0-9])\d{9}$/).test(form.account)) {
    $toast('请输入正确的手机号码');
    return;
  }
  sendPhoneVCode({ mobile: form.account }).then((res: any) => {
    $toast('验证码发送成功');
    codeObj.timeout = setInterval(() => {
      if (codeObj.count < 1) {
        codeObj.disabled = false;
        codeObj.codeName = '重新获取';
        codeObj.count = 120;
        clearInterval(codeObj.timeout);
      } else {
        codeObj.disabled = true;
        codeObj.codeName = `${codeObj.count--}s后重发`;
      }
    }, 1000);
  });
};

// 密码切换
let isPwd = ref(true);
const tapPwd = () => {
  isPwd.value = !isPwd.value;
};

// 忘记密码
const tapForgot = () => {
  uni.navigateTo({
    url: `/pages/login/forgotPwd`,
  });
};

// 登录
const checkLogin = async () => {
  console.log('222222222------------');
  if (!form.account) {
    $toast(action.value === '1' ? '请输入手机号' : '请输入账号');
    return;
  }
  if (action.value === '1' && !new RegExp(/^(1[0-9])\d{9}$/).test(form.account)) {
    $toast('请输入正确的手机号码');
    return;
  }
  if (action.value === '2' && !new RegExp(/^(?!^\d+$)[0-9a-zA-Z_]*$/).test(form.account)) {
    $toast('账号只能输入字母或字母+数字');
    return;
  }
  if (action.value === '1' && !form.code) {
    $toast('请输入验证码');
    return;
  }
  if (action.value === '2' && !form.password) {
    $toast('请输入密码');
    return;
  }
  console.log('222222222------ffff------', checkAgreement.value);
  if (!checkAgreement.value) {
    // $toast('请勾选协议');
    showgreement(1);
    return;
  }
  const ruleForm = {} as any;
  if (action.value === '1') {
    ruleForm.mobile = form.account;
    ruleForm.verificationCode = form.code;
    ruleForm.cityName = getLocationInfo().cityName;
  } else if (action.value === '2') {
    ruleForm.userName = form.account;
    ruleForm.password = getMd5(form.password);
  }
  // 获取code
  // const code = await uniLogin('weixin');
  // #ifdef MP-WEIXIN
  if (openid.value) {
    ruleForm.openId = openid.value;
  } else {
    const code = await uniLogin('weixin');
    ruleForm.code = code;
  }
  // if (!code) return;
  // #endif
  console.log('222222222------333------');
  if (action.value === '1') {
    loginWithCode(ruleForm).then((res: any) => {
      if (res?.length === 1) {
        setToken(res[0].token);
        setUserId(res[0].userId);
        setOpenId(res[0].openId);
        setMoreCharge(res[0].moreCharging);
        backPage(page.value);
      } else if (res?.length > 1) {
        popupUserRef.value?.show(res, page.value);
      }
    });
  } else if (action.value === '2') {
    loginWithPassword(ruleForm).then((res: any) => {
      setToken(res.token);
      setUserId(res.userId);
      setOpenId(res.openId);
      setMoreCharge(res.moreCharging);
      backPage(page.value);
    });
  }
};
let tapLogin = async () => {
  checkLogin();
};

// 协议
const tapAgreement = () => {
  checkAgreement.value = !checkAgreement.value;
};

// 微信授权登录
let tapWx = () => {
  console.log('111111111111------------');
  if (!checkAgreement.value) {
    showgreement(2);
    return;
    // $toast('请勾选协议');
  }
};
let bindPhoneNumber = async (e: any) => {
  console.log(e.detail);
  const res = e.detail;
  if (!res.code) {
    console.log('bindPhoneNumber---------', e.detail);
    $toast(`授权失败!${e.detail.errMsg}${e.detail.errNo || ''}`);
    return;
  }
  // const jscode = await uniLogin('weixin');
  // if (!jscode) return;
  if (!openid.value) {
    $toast(`获取openId失败，请重新授权！`);
    getOpenId();
    return;
  }
  const name = getLocationInfo().cityName;
  loginWithWx({
    cityName: name,
    code: res.code,
    // jsCode: jscode,
    openId: openid.value,
    phoneNumberInfo: {
      encryptedData: res.encryptedData,
      iv: res.iv,
    },
  }).then((res: any) => {
    if (res?.length === 1) {
      setToken(res[0].token);
      setUserId(res[0].userId);
      setOpenId(res[0].openId);
      setMoreCharge(res[0].moreCharging);
      backPage(page.value);
    } else if (res?.length > 1) {
      popupUserRef.value?.show(res, page.value);
    }
  });
};

const tapAgreementUrl = () => {
  const url = `${import.meta.env.VITE_VUE_APP_RES}${
    import.meta.env.VITE_VUE_APP_AGREEMENT
  }agreement-user.html`;
  uni.navigateTo({
    url: `/pagesMain/webView/webView?url=${url}`,
  });
};

const showgreement = (type: number) => {
  popupAgreementRef.value.show(type);
};
const setAgreement = (e: any) => {
  checkAgreement.value = true;
  if (e) {
    bindPhoneNumber(e);
  } else {
    checkLogin();
  }
};

// #ifdef H5
// 左上角返回
const onClickLeft = () => {
  const pages = getCurrentPages();
  // console.log('pages', pages);
  if (pages.length <= 1) {
    uni.reLaunch({
      url: `/pages/stationMap/stationMap`,
    });
  } else {
    uni.navigateBack();
  }
};
setTimeout(() => {
  const navBarEle = document.querySelector('.van-nav-bar') as HTMLElement;
  navBarEle.style.paddingTop = `${systemInfo.statusBarHeight}px`;
});
// #endif
</script>
<style lang="scss" scoped>
@import './login.scss';

.login-wrap {
  position: relative;
  height: 100vh;
  overflow-y: auto;
  overflow-x: hidden;
  // #ifdef H5
  overflow: hidden;
  display: flex;
  flex-direction: column;
  // #endif
  // #ifdef H5
  .login-top {
    flex: 1;
    overflow-y: scroll;
    overflow-x: hidden;
  }
  // #endif

  .header {
    position: relative;
    height: 180px;
    background-color: $uni-color-primary;

    .text {
      position: absolute;
      top: 4px;
      left: 24px;
      line-height: 30px;
      font-size: 20px;
      letter-spacing: 4.5px;
      color: #fff;
      white-space: pre-wrap;
      word-break: break-all;
      word-wrap: break-word;
    }

    .car {
      position: absolute;
      width: 298px;
      height: 180px;
      top: 13px;
      left: 87px;
      background-image: url($url + 'login/bg-car.png');
      background-size: 100%;
      background-repeat: no-repeat;
    }

    .bg1 {
      position: absolute;
      width: 170px;
      height: 130px;
      top: 39px;
      left: -5px;
      background-image: url($url + 'login/bg1.png');
      background-size: 100%;
      background-repeat: no-repeat;
    }

    .bg2 {
      position: absolute;
      width: 103.5px;
      height: 46.5px;
      top: 128px;
      left: 281.5px;
      background-image: url($url + 'login/bg2.png');
      background-size: 100%;
      background-repeat: no-repeat;
    }

    .bg3 {
      position: absolute;
      width: 62px;
      height: 20px;
      top: 5px;
      left: 166px;
      background-image: url($url + 'login/bg3.png');
      background-size: 100%;
      background-repeat: no-repeat;
    }

    .bg4 {
      position: absolute;
      width: 88px;
      height: 44px;
      top: 28px;
      left: 275px;
      background-image: url($url + 'login/bg4.png');
      background-size: 100%;
      background-repeat: no-repeat;
    }
  }

  .title-wrap {
    position: relative;
    display: flex;
    justify-content: space-around;
    width: 240px;
    height: 40px;
    line-height: 40px;
    margin: 32px auto;
    background-color: #f2f2f2;
    font-size: 14px;
    border-radius: 90px;

    .title-action {
      position: absolute;
      width: 120px;
      height: 40px;
      // left: 0;
      background-color: $uni-color-primary;
      border-radius: 90px;
    }

    .action {
      position: relative;
      color: #fff;
    }

    .action1 {
      animation-name: example1;
      animation-duration: 0.1s;
      animation-fill-mode: forwards;
    }

    @keyframes example1 {
      from {
        left: 50%;
      }

      to {
        left: 0;
      }
    }

    .action2 {
      animation-name: example2;
      animation-duration: 0.1s;
      animation-fill-mode: forwards;
    }

    @keyframes example2 {
      from {
        left: 0;
      }

      to {
        left: 50%;
      }
    }
  }

  .login-form {
    margin: 32px 32px 0 32px;
  }

  .forgot-pwd {
    margin: 0;
    padding: 0;
    font-size: 14px;
    color: $uni-color-primary;
    border: 0;
  }

  .row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 32px;
  }

  .agreement-wrap {
    display: flex;
    justify-content: center;
    align-items: center;

    .radio-wrap {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 20px;
      height: 20px;
      margin-right: 8px;
    }

    .radio-radius {
      border: 1px solid #bdbdbd;
      border-radius: 50%;
      box-sizing: border-box;
    }

    text {
      line-height: 22px;
      font-size: 14px;
    }

    .text1 {
      color: $uni-color-primary;
    }
  }

  .bnt-bottom {
    display: flex;
    flex-direction: column;
    position: absolute;
    left: 32px;
    bottom: constant(safe-area-inset-bottom);
    bottom: env(safe-area-inset-bottom);
    // #ifdef H5
    position: relative;
    left: 0;
    // #endif
  }

  .bnt-login {
    width: 311px;
    height: 44px;
    border-radius: 100px;
    font-size: 16px;
  }

  .bnt-login-wx {
    width: 311px;
    height: 44px;
    margin-top: 20px;
    border-radius: 100px;
    font-size: 16px;
    background-color: #07c160;
  }

  .bnt-hidden {
    visibility: hidden;
  }

  .tip {
    display: flex;
    align-items: center;
    justify-content: center;
    line-height: 22px;
    margin-top: 20px;
    margin-bottom: 18px;
    font-size: 14px;
    color: #666;
  }
}
.van-nav-bar {
  background-color: #5073f7;
}
</style>